package com.boang.handler;

import com.alibaba.fastjson2.JSONObject;
import com.boang.feign.TokenFeign;
import com.boang.resp.Result;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/*
  @author: 13813
  @date: 2024/9/11 9:31
*/
@Component
public class TokenHandler extends OncePerRequestFilter {

    @Autowired
    TokenFeign tokenFeign;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        Result<String> result = tokenFeign.verificationToken(token);
        if (result.getCode() == 200) {
            filterChain.doFilter(request, response);
        } else {
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSONObject.toJSONString(Result.failed("验证失败")));
        }
    }
}
